<template>
  <div class="container">
    <el-card shadow="always" class="login-box">
      <h1 slot="header" class="clearfix">欢迎现代眼镜客户管理系统</h1>
      <el-form ref="login" label-position="right" :rules="rules" :model="form">
        <el-form-item prop="useranme">
          <el-input prefix-icon="el-icon-user" v-model="form.useranme"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-key" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width:100%" :loading="isLogin" @click="submit" variant="primary">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request, { setToken } from '@/api/index'

export default {
  meta: {
    auth: false
  },
  name: 'login',
  data () {
    return {
      form: {
        useranme: '',
        password: ''
      },
      rules: {
          useranme: [
            { required: true, message: '请输入用户名'},
            { min: 5, max: 16, message: '长度在 5 到 16 个字符' }
          ],
          password: [
            { required: true, message: '请输入密码' },
            { min: 6, max: 16, message: '长度在 6 到 16 个字符' }
          ]
      },
      isLogin: false
    }
  },
  computed: {
    redirect () {
      return this.$store.state.user.loginRedirect
    }
  },
  methods: {
    async submit () {
      if (this.isLogin) {
        return
      }
      this.isLogin = true

      try {
        await this.$refs['login'].validate()
        const data = await request('login', this.form)
        setToken(data.token)
        this.$nextTick(() => {
          let route = this.redirect
          if (!route) {
            route = {
              name: 'dashboard'
            }
          }
          this.isLogin = false
          this.$router.push(route)
        })
      } catch (e) {}
        this.isLogin = false
    }
  }
}
</script>

<style scoped>
.container {
  position: fixed;
  height: 100%;
  width: 100%;
  overflow: hidden;
}
.login-box {
  width:350px;
  position: absolute;
  left: 0;
  right: 0;
  margin: 130px auto 0;
}
</style>
